package driver.android;


import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import driver.android.adapter.TaskSummaryDetailListAdapter;
import driver.android.adapter.TaskSummaryListAdapter;
import driver.android.http.CommonOkHttpClient;
import driver.util.Constants;
import driver.util.Event;
import driver.util.IHttpCallBack;
import driver.util.Util;
import okhttp3.Response;

public class FlashDriverSummaryActivity extends Activity implements IHttpCallBack, AdapterView.OnItemClickListener {

    private String[] monthStringValues;
    private String[] dayOfWeekValues;
    private TextView txtYear;
    private TextView txtMonth;
    private TextView txtDayOfWeek;
    private TextView txtDate;
    private Animation txtDateAnim;
    private Animation txtYearAnim;
    private Animation txtMonthAnim;
    private Animation txtDayOfWeekAnim;
    private String mLoginToken;
    private String mUuid;
    private SharedPreferences mFlashSharedPreferences;
    private String mFlashSharePreferenceName = "Flash";
    private ProgressDialog mProgressDialog;
    private FlashDriverTaskHandler mHandler;
    private TextView txtEarningSub;
    private TextView txtEarningValue;
    private TextView txtPaySub;
    private TextView txtPayValue;
    private TextView txtUnPaySub;
    private TextView txtUnPayValue;
    private List<TextView> mSubs;
    private List<TextView> mSubValue;
    private ListView mSummaryList;
    private TaskSummaryListAdapter mTaskSummaryListAdapter;
    private List<Event> mSummaryTaskList = new ArrayList<Event>();
    private Button mChangeDateBtn;
//    private boolean mClickStartTime = true;
    private Button mBack;
    private TextView mTimeRangeText;
    private RelativeLayout mTimeDateLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.f_activity_earning);
        initSetting();
        getEarningsDetail(null, null);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Util.debugApp('d', "支付摘要activity on pause");
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void initSetting() {
        mHandler = new FlashDriverTaskHandler(this);
        monthStringValues = this.getResources().getStringArray(R.array.month_type_array);
        dayOfWeekValues = this.getResources().getStringArray(R.array.day_of_week_type_array);
        txtYear = (TextView) this.findViewById(R.id.txt_year);
        txtMonth = (TextView) this.findViewById(R.id.txt_month);
        txtDayOfWeek = (TextView) this.findViewById(R.id.txt_day_of_week);
        txtDate = (TextView) this.findViewById(R.id.txt_date);
        txtDateAnim = AnimationUtils.loadAnimation(this, R.anim.scale_0_to_1);
        txtYearAnim = AnimationUtils.loadAnimation(this, R.anim.bottom_to_top_slide_in);
        txtMonthAnim = AnimationUtils.loadAnimation(this, R.anim.bottom_to_top_slide_in);
        txtDayOfWeekAnim = AnimationUtils.loadAnimation(this, R.anim.bottom_to_top_slide_in);
        txtDateAnim.setAnimationListener(new AnimationHandler(txtYear, txtYearAnim));
        txtYearAnim.setAnimationListener(new AnimationHandler(txtMonth, txtMonthAnim));
        txtMonthAnim.setAnimationListener(new AnimationHandler(txtDayOfWeek, txtDayOfWeekAnim));
        txtDayOfWeekAnim.setAnimationListener(new AnimationHandler(null, null));
        Calendar calendar = Calendar.getInstance();
        txtYear.setText(String.valueOf(calendar.get(Calendar.YEAR)));
        txtMonth.setText(monthStringValues[calendar.get(Calendar.MONTH)]);
        txtDayOfWeek.setText(dayOfWeekValues[calendar.get(Calendar.DAY_OF_WEEK) - 1]);
        txtDate.setText(String.valueOf(calendar.get(Calendar.DATE)));
        txtDate.startAnimation(txtDateAnim);
        Util.debugApp('d', "获取的年周几/日信息 " + String.valueOf(calendar.get(Calendar.YEAR)) + " " + (calendar.get(Calendar.DAY_OF_WEEK) - 1) + " " + String.valueOf(calendar.get(Calendar.DATE)));
        mFlashSharedPreferences = getSharedPreferences(mFlashSharePreferenceName, Context.MODE_PRIVATE);
        mLoginToken = mFlashSharedPreferences.getString("token", "");
        mUuid = mFlashSharedPreferences.getString("uuid", "");
        mProgressDialog = new ProgressDialog(this);
        txtEarningSub = this.findViewById(R.id.total_earning_sub);
        txtEarningValue = this.findViewById(R.id.total_earning_value);
        txtPaySub = this.findViewById(R.id.total_pay_sub);
        txtPayValue = this.findViewById(R.id.total_pay_value);
        txtUnPaySub = this.findViewById(R.id.total_un_paid_sub);
        txtUnPayValue = this.findViewById(R.id.total_up_paid_value);
        mTimeRangeText = this.findViewById(R.id.txt_time_range);
        mTimeRangeText.setText("");
        mTimeRangeText.setVisibility(View.INVISIBLE);
        mTimeDateLayout = this.findViewById(R.id.time_date_layout);
        mTimeDateLayout.setVisibility(View.VISIBLE);
        mBack = this.findViewById(R.id.back_package_list_button);
        mSubs = new ArrayList<>();
        mSubValue = new ArrayList<>();
        mSubs.add(txtEarningSub);
        mSubs.add(txtPaySub);
        mSubs.add(txtUnPaySub);
        mSubValue.add(txtEarningValue);
        mSubValue.add(txtPayValue);
        mSubValue.add(txtUnPayValue);
        mSummaryList = this.findViewById(R.id.summary_list);
        mTaskSummaryListAdapter = new TaskSummaryListAdapter(this, R.layout.f_task_summary_item, mSummaryTaskList);
        mSummaryList.setAdapter(mTaskSummaryListAdapter);
        mSummaryList.setOnItemClickListener(this);
        mChangeDateBtn = this.findViewById(R.id.month_history_button);
        mChangeDateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Dialog dialog = createCustomDateDialog();
                if (dialog != null && !dialog.isShowing()) {
                    dialog.show();
                }
            }
        });
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(FlashDriverSummaryActivity.this, FlashDriverPackageListActivity.class);
                FlashDriverSummaryActivity.this.startActivity(intent);
                FlashDriverSummaryActivity.this.finish();
            }
        });
    }

    private void getEarningsDetail(String start, String end) {
        if (mLoginToken != null && mUuid != null) {
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            Util.debugApp('d', "今天的日期" + formatter.format(calendar.getTime()));
            String dateBegin = formatter.format(calendar.getTime());
            calendar.add(calendar.DATE, 1);
            String dateEnd = formatter.format(calendar.getTime());
            Util.debugApp('d', "开始查询支付摘要信息 " + dateBegin + " " + dateEnd);
            CommonOkHttpClient okHttpInstance = CommonOkHttpClient.getInstance(this);
            Map<String, String> headersParams = new HashMap<>();
            headersParams.put("token", mLoginToken);
//            date_begin=2021-02-03&date_end=2021-02-04
            if (Util.DEBUG_DATE) {
                dateBegin = "2021-02-18";
                dateEnd = "2021-02-22";
            }
            if (start != null && end != null) {
                dateBegin = start;
                dateEnd = end;
            }
            String url = Constants.ROOT + mUuid + Constants.EARNINGS + "?date_begin=" + dateBegin + "&date_end=" + dateEnd;
            Util.debugApp('d', "获取支付摘要url " + url);
            okHttpInstance.doGet(url, headersParams, null);
        }
    }

    private void showProgressDialog(String title) {
        if (mProgressDialog != null) {
            mProgressDialog.setMessage(title);
            mProgressDialog.setCanceledOnTouchOutside(false);
            if (!this.isFinishing()) {
                mProgressDialog.show();
            }
        }
    }

    private void closeProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    private void handlerNetWorkError() {
        Toast.makeText(this, "Sorry, NetWork Error...", Toast.LENGTH_SHORT).show();
    }

    private void showToast(String title) {
        Toast.makeText(this, title, Toast.LENGTH_LONG).show();
    }

    private void showLoginActivity() {
        SharedPreferences.Editor editor = mFlashSharedPreferences.edit();
        editor.putString("token", "");
        editor.putString("uuid", "");
        editor.commit();
        Intent intent = new Intent();
        intent.setClass(this, FlashDriverLoginActivity.class);
        this.startActivity(intent);
        this.finish();
    }

    private void parseJsonBundle(Bundle bundle) {
        mSummaryTaskList.clear();
        String taskJsonDetail = bundle.getString("taskBody");
        Util.debugApp('d', "开始解析远端内容" + taskJsonDetail);
        String summary = Util.getJsonKeyValue("summary", taskJsonDetail) == null ? "" : Util.getJsonKeyValue("summary", taskJsonDetail);
        parseSummary(summary);
        String details = Util.getJsonKeyValue("details", taskJsonDetail) == null ? "" : Util.getJsonKeyValue("details", taskJsonDetail);
        parseDetail(details);
    }

    private void parseDetail(String details) {
        Util.debugApp('d', "parseDetail " + details);
        if (details.length() > 0) {
            try {
                JSONArray jsonSummaryArray = new JSONArray(details);
                int length = jsonSummaryArray.length();
                for (int index = 0; index < length; index++) {
                    Event event = new Event();
                    String item = jsonSummaryArray.get(index).toString();
                    String header = Util.getJsonKeyValue("header", item) == null ? "" : Util.getJsonKeyValue("header", item);
                    String start_time = Util.getJsonKeyValue("start_time", item) == null ? "" : Util.getJsonKeyValue("start_time", item);
                    String end_time = Util.getJsonKeyValue("end_time", item) == null ? "" : Util.getJsonKeyValue("end_time", item);
                    String total = Util.getJsonKeyValue("total", item) == null ? "" : Util.getJsonKeyValue("total", item);
                    event.setHeader(header);
                    event.setStart_time(start_time);
                    event.setEnd_time(end_time);
                    event.setTotal(total);
                    String detail = Util.getJsonKeyValue("detail", item) == null ? "" : Util.getJsonKeyValue("detail", item);
                    event.setDetail(detail);
                    mSummaryTaskList.add(event);
                }
                if (mSummaryTaskList.size() > 0) {
                    mTaskSummaryListAdapter.notifyDataSetChanged();
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Util.debugApp('d', "parseDetail异常");
            }
        }
    }

    private void parseSummary(String summary) {
        if (summary.length() > 0) {
            try {
                JSONArray jsonSummaryArray = new JSONArray(summary);
                int length = jsonSummaryArray.length();
                for (int index = 0; index < length; index++) {
                    String taskItemJson = jsonSummaryArray.get(index).toString();
                    Util.debugApp('d', "查询到正在执行的任务内容为 " + taskItemJson);
                    String state = Util.getJsonKeyValue("item", taskItemJson) == null ? "" : Util.getJsonKeyValue("item", taskItemJson);
                    String taskId = Util.getJsonKeyValue("value", taskItemJson) == null ? "" : Util.getJsonKeyValue("value", taskItemJson);
                    Util.debugApp('d', "储存summary信息 " + state + " " + taskId);
                    mSubs.get(index).setText(state + ":");
                    mSubValue.get(index).setText(" " + taskId);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Util.debugApp('d', "获取summary异常");
            }
        }
    }

    @Override
    public void success(Response response) {
        Message getTaskSuccessMessage = mHandler.obtainMessage();
        Bundle bundle = new Bundle();
        try {
            String body = response.body().string();
            getTaskSuccessMessage.what = Constants.EARNING_DETAIL_SUCCESS;
            bundle.putString("taskBody", body);
            getTaskSuccessMessage.setData(bundle);
            Util.debugApp('d', "获取远端信息成功body " + body);
        } catch (IOException e) {
            Util.debugApp('e', "获取远端信息成功但是转换失败" + e.toString());
            getTaskSuccessMessage.what = Constants.EARNING_DETAIL_FAIL;
        }
        mHandler.sendMessage(getTaskSuccessMessage);
    }

    @Override
    public void fail(IOException exception) {
        if (mHandler != null) {
            Message getTaskFailMessage = mHandler.obtainMessage();
            if (getTaskFailMessage != null) {
                getTaskFailMessage.what = Constants.EARNING_DETAIL_FAIL;
                mHandler.sendMessage(getTaskFailMessage);
                Util.debugApp('d', "获取远端信息失败" + exception.toString());
            }
        }
    }

    @Override
    public void codeInvalid(Response response) {
        if (mHandler != null) {
            Message unKnowMessage = mHandler.obtainMessage();
            if (unKnowMessage != null) {
                int code = response.code();
                if (code == 401) {
                    unKnowMessage.what = Constants.UN_KNOW_RESPONSE_401_CODE;
                } else {
                    try {
                        String body = response.body().string();
                        Util.debugApp('d', "codeInvalid " + body);
                        Bundle bundle = new Bundle();
                        bundle.putString("codeInvalid", body);
                        unKnowMessage.what = Constants.UN_KNOW_RESPONSE_CODE;
                        unKnowMessage.setData(bundle);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                mHandler.sendMessage(unKnowMessage);
            }
        }
    }

    /**
     * 设置EditText有焦点时隐藏输入法
     * author 000
     * @param activity
     * @param editText
     */
    public static void setSoftInputOnFocusShow(Activity activity, EditText editText) {
        if (Build.VERSION.SDK_INT <= 10) {
            editText.setInputType(InputType.TYPE_NULL);
        } else {
            activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            try {
                Class<EditText> cls = EditText.class;
                Method setSoftInputShownOnFocus;
                setSoftInputShownOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
                setSoftInputShownOnFocus.setAccessible(true);
                setSoftInputShownOnFocus.invoke(editText, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private Dialog createCustomDateDialog() {
        Dialog baseDialog = new Dialog(this, R.style.BaseDialog);
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.f_change_date_dialog_layout, null);
        baseDialog.setContentView(layout);
        baseDialog.setCanceledOnTouchOutside(true);
        Button updateAppCancelVersionBtn = (Button) layout.findViewById(R.id.update_cancel_version_button);
        Button cancelSelectDataPicker = (Button) layout.findViewById(R.id.cancel_select_Data_pick_button);
        CalendarView datePicker = layout.findViewById(R.id.datePicker);
        EditText startTime = layout.findViewById(R.id.tv_date);
        setSoftInputOnFocusShow(this, startTime);
        String wholeTime = mTimeRangeText.getText().toString();
        Util.debugApp('d', "当前的时间跨度为" + wholeTime);
        if (wholeTime.length() > 0 && wholeTime.contains("~")) {
            String startT = wholeTime.substring(0, wholeTime.indexOf('~')).trim();
            Util.debugApp('d', "当前的时间跨度为startT" + startT);
            startTime.setText(startT.trim());
        } else {
            startTime.setText("");
        }
//        startTime.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
////                datePicker.setVisibility(View.VISIBLE);
////                mClickStartTime = true;
//            }
//        });
        EditText endTime = layout.findViewById(R.id.tv_date_end);
        setSoftInputOnFocusShow(this, endTime);
        if (wholeTime.length() > 0 && wholeTime.contains("~")) {
            String endT = wholeTime.substring(wholeTime.indexOf('~') + 1).trim();
            Util.debugApp('d', "当前的时间跨度为endT" + endT);
            endTime.setText(endT);
        } else {
            endTime.setText("");
        }
//        endTime.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
////                datePicker.setVisibility(View.VISIBLE);
//                mClickStartTime = false;
//            }
//        });
        if (updateAppCancelVersionBtn != null) {
            updateAppCancelVersionBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String start = startTime.getText().toString();
                    String end = endTime.getText().toString();
                    if (start.isEmpty() || end.isEmpty()) {
                        showToast("Please select start time and end time");
                        return;
                    }
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        Date startDate = dateFormat.parse(start);
                        Date endDate = dateFormat.parse(end);
                        if (endDate.before(startDate)) {
                            showToast("Please select correct end time");
                            return;
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    baseDialog.dismiss();
                    mTimeRangeText.setVisibility(View.VISIBLE);
                    mTimeRangeText.setText(startTime.getText().toString() + " ~ " + endTime.getText().toString());
                    mTimeDateLayout.setVisibility(View.INVISIBLE);
                    showProgressDialog("Please wait...");
                    getEarningsDetail(startTime.getText().toString(), endTime.getText().toString());
                }
            });
        }
        if (cancelSelectDataPicker != null) {
            cancelSelectDataPicker.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (baseDialog != null) {
                        baseDialog.dismiss();
                    }
                }
            });
        }
        datePicker.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) {
                if (startTime.hasFocus()) {
                    startTime.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
                } else {
                    endTime.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
                }
//                if (mClickStartTime) {
//                    startTime.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
//                } else {
//                    endTime.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
//                }
//                datePicker.setVisibility(View.GONE);
            }
        });
        return baseDialog;
    }

    private Dialog createCustomUpdateDialog(Event event) {
        Dialog baseDialog = new Dialog(this, R.style.BaseDialog);
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.f_summary_detail_dialog_layout, null);
        TextView totalEarn = layout.findViewById(R.id.start_time_text_view);
//        TextView endTime = layout.findViewById(R.id.end_time_text_view);
        totalEarn.setText("Earn: " + event.getTotal());
//        endTime.setText("end time:" + event.getEnd_time());
        ListView summaryDetailList = layout.findViewById(R.id.lvTrace);
        TaskSummaryDetailListAdapter eventListAdapter = new TaskSummaryDetailListAdapter(this, event);
        summaryDetailList.setAdapter(eventListAdapter);
        baseDialog.setContentView(layout);
        Button updateAppCancelVersionBtn = (Button) layout.findViewById(R.id.update_cancel_version_button);
        if (updateAppCancelVersionBtn != null) {
            updateAppCancelVersionBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    baseDialog.dismiss();
                }
            });
        }
        return baseDialog;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Event event = (Event) mSummaryList.getAdapter().getItem(position);
        Dialog dialog = createCustomUpdateDialog(event);
        if (dialog != null && !dialog.isShowing()) {
            dialog.show();
        }
    }

    private static class FlashDriverTaskHandler extends Handler {

        private final WeakReference<FlashDriverSummaryActivity> mActivity;

        private FlashDriverTaskHandler(FlashDriverSummaryActivity ac) {
            this.mActivity = new WeakReference<FlashDriverSummaryActivity>(ac);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            FlashDriverSummaryActivity activity = mActivity.get();
            if (activity != null) {
                activity.closeProgressDialog();
                switch (msg.what) {
                    case Constants.EARNING_DETAIL_SUCCESS:
                        Util.debugApp('d', "获取任务成功的消息");
                        Bundle bundle = msg.getData();
                        activity.parseJsonBundle(bundle);
                        break;
                    case Constants.EARNING_DETAIL_FAIL:
                        Util.debugApp('d', "获取任务失败的消息");
                        activity.handlerNetWorkError();
                        break;
                    case Constants.UN_KNOW_RESPONSE_401_CODE:
                        activity.showLoginActivity();
                        break;
                    case Constants.UN_KNOW_RESPONSE_CODE:
                        Bundle bundleUnKnowCode = msg.getData();
                        String unKnowBody = bundleUnKnowCode.getString("codeInvalid");
                        String description = Util.getJsonKeyValue("description", unKnowBody);
                        if (description == null) {
                            activity.showToast("Network Error");
                        } else {
                            activity.showToast(description);
                        }
                        break;
                }
            }
        }
    }

    private class AnimationHandler implements Animation.AnimationListener {

        private TextView nextTextView;
        private Animation nextAnimation;

        public AnimationHandler(TextView nextTextView, Animation nextAnimation) {
            this.nextTextView = nextTextView;
            this.nextAnimation = nextAnimation;
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            if (nextTextView != null && nextAnimation != null) {
                nextTextView.startAnimation(nextAnimation);
            }
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

        @Override
        public void onAnimationStart(Animation animation) {

        }
    }
}
